#!/usr/local/bin/python2.7

import writer, os, string
from constants import *

os.environ['DJANGO_SETTINGS_MODULE'] = 'djangodb.settings'
from djangodb.forum.models import *
import djangodb
import djangodb.forum

#os.putenv('DJANGO_SETTINGS_MODULE', 'djangodb.settings')

class DjangoWriter(writer.Writer):

    def __init__(self):
        writer.Writer.__init__(self)
        self._extension = ''

        self._core = DbComponent()

    def _writeIt(self):
        
        self._reset()
        self._buildCore()
        self._buildPics()
        self._buildFlows()
        self._buildDrawings()
        self._buildSubDicts()
        
    def _reset(self):
        self._core = DbComponent()

    def _buildCore(self):
        mydict = self._component.getDict('gen')
        keys = ['SystemName', 'SystemNumber', \
            'UniqueIDNumber', 'ItemName', 'BuildingNumber', 'Location', \
            'CriticalComponent', 'AdditionalIdentifiers']
        vals = []
        for key in keys:
            vals.append(','.join(mydict[key])[:254].strip())
        myter = iter(vals)

        self._core.system_name = myter.next()
        self._core.system_number = myter.next()
        self._core.unique_id = myter.next()
        self._core.item_name = myter.next()
        self._core.building_number = myter.next()
        self._core.location = myter.next()
        self._core.is_critical = myter.next()
        self._core.additional_identifiers = myter.next()

        self._core.save()

    def _buildPics(self):
        for pic in self._component.getPics():
            name, path = pic.name, pic.path

            db_entry = DbPicture()

            db_entry.component = self._core
            db_entry.root_directory = path
            base, ext = os.path.splitext(name)
            db_entry.file_name = base
            db_entry.file_extension = ext.replace('.', '')

            db_entry.save()

    def _buildFlows(self):
        dict_names = ['mech', 'elec', 'iandc']
        types = ['To', 'From']

        for name in dict_names:
            for direc in types:
                if len(self._component.getValue(name, direc)) > 0:
                    db_entry = DbFlow()

                    db_entry.component = self._core
                    db_entry.sub_type = name
                    db_entry.to_or_from = direc
                    db_entry.what = \
                        ', '.join(self._component.getValue(name, direc))[:254]

                    db_entry.save()

    def _buildDrawings(self):
        text = self._component.getValue('gen', 'Drawings')
        drawings = ','.join(text).split(',')
        for drawing in drawings:
            drawing = ''.join([c for c in drawing if c in '1234567890'])

            db_entry = DbDrawing()
            db_entry.component = self._core
            db_entry.drawing_number = drawing
            db_entry.save()

    def _buildSubDicts(self):
        dicts = {'mech':self._buildMech, 'elec':self._buildElec, \
                 'iandc':self._buildIandC}

        for dict_name in dicts:
            sub_dict = self._component.getDict(dict_name)
            for key, vals in sub_dict.items():
                if len(vals) > 0:
                    dicts[dict_name]()
                    break

    def _buildMech(self):
        mydict = self._component.getDict('mech')
        keys = ['Manufacturer', 'ModelNumber', 'SerialNumber', \
                'Size', 'FlowRates', 'RPM', 'Material']
        vals = []
        for key in keys:
            vals.append(', '.join(mydict[key])[:254])
        myter = iter(vals)

        db_entry = DbMechanical()

        db_entry.component = self._core
        db_entry.manufacturer = myter.next()
        db_entry.model_number = myter.next()
        db_entry.serial_number = myter.next()
        db_entry.size = myter.next()
        db_entry.flowrates = myter.next()
        db_entry.rpm = myter.next()
        db_entry.material = myter.next()

        db_entry.save()
        
    def _buildElec(self):
        mydict = self._component.getDict('elec')
        keys = ['Manufacturer', 'ModelNumber', 'SerialNumber', \
                'HorsePower', 'RPM', 'Volts', 'Hertz', 'Phase', 'Amps']
        vals = []
        for key in keys:
            vals.append(', '.join(mydict[key])[:254])
        myter = iter(vals)

        db_entry = DbElectrical()

        db_entry.component = self._core
        db_entry.manufacturer = myter.next()
        db_entry.model_number = myter.next()
        db_entry.serial_number = myter.next()
        db_entry.horse_power = myter.next()
        db_entry.rpm = myter.next()
        db_entry.volts = myter.next()
        db_entry.hertz = myter.next()
        db_entry.phase = myter.next()
        db_entry.amps = myter.next()

        db_entry.save()
        
    def _buildIandC(self):
        mydict = self._component.getDict('iandc')
        keys = ['Manufacturer', 'ModelNumber', 'SerialNumber', \
                'OutputRange', 'DisplayRange', 'Medium', 'AnalogorDigital']
        vals = []
        for key in keys:
            vals.append(', '.join(mydict[key])[:254])
        myter = iter(vals)

        db_entry = DbIandC()

        db_entry.component = self._core
        db_entry.manufacturer = myter.next()
        db_entry.model_number = myter.next()
        db_entry.serial_number = myter.next()
        db_entry.output_range = myter.next()
        db_entry.display_range = myter.next()
        db_entry.medium = myter.next()
        db_entry.analog_or_digital = myter.next()

        db_entry.save()

